<template>
  <el-container class="udibind">
    <el-form ref="form" label-width="120px"  class="box-card"  @submit.native.prevent>
      <el-card class="box-card"  style="    width: 70%;margin: auto auto;" shadow="always" >
        <el-row  justify="center" type="flex" >
          <el-col :span="12">
            <el-form-item label="请扫描SN或者UDI" size="large" label-width="200px" >
              <el-input ref="txtScan" v-model="txtScan" placeholder="SN/UDI" @keyup.native.enter="barCodeScan"  ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="" size="large" label-width="0px"  style="    padding-left: 22px;">
              <el-button type="success" @click="bind">绑定</el-button>
              <el-button ref="resetUdi" :disabled="form.udi == null || form.udi == ''" @click="resetUdi">重置udi</el-button>
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row  justify="center" type="flex" >
          <el-col :span="24">
            <el-form-item label=""  label-width="0px" style="margin: 0px;">
              <el-alert style="padding: 3px 0px;"
                        effect="dark"
                        title="扫描SN或者UDI标签进行检索，若存在库存，则可以进行绑定解绑操作"
                        type="warning"
                        :closable="false"
                        show-icon>
              </el-alert>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="box-card"  style="    width: 80%;margin: auto auto;    margin-top: 22px;" shadow="always">
        <div slot="header" class="clearfix">
          <h2>库存信息</h2>
        </div>
        <div class="text item">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="耗材名称" style="margin-bottom: -12px;">
                <el-input v-model="form.matrName" readonly  />
                <el-input v-model="form.id" type="hidden"  />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="耗材品规">
                <el-input v-model="form.matrSpec" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="text item">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="供应商">
                <el-input v-model="form.supplierName" readonly  />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="批次">
                <el-input v-model="form.lot" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="生产日期">
                <el-input v-model="form.mfgDate" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="有效期">
                <el-input v-model="form.expDate" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="text item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="包装单位">
                <el-input v-model="form.packageUnit" readonly  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="包装单品数量">
                <el-input v-model="form.skuQty" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="厂商">
                <el-input v-model="form.mfgName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="text item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="SN码">
                <el-input v-model="form.sn" readonly  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="RFID">
                <el-input v-model="form.rfid" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="UDI">
                <el-input v-model="form.udi" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div >
          <data-view
            ref="dataViewSN"
            propViewKey="wm_stock_udibind"
            :propAutoFetchData=false
            :propHideQueryButton=true
            :propParentPage="_self"
            @extra-button-click="extraButtonClick"
          />
        </div>
      </el-card>
    </el-form>
  </el-container>
</template>

<script>
import barcodeParse from '@/util/barcodeParse.js'

export default {
  data() {
    return {
      form: {
        matrId: '',
        supplierId: '',
        matrName: '',
        id: '',
        matrSpec: '',
        supplierName: '',
        lot: '',
        mfgDate: '',
        expDate: '',
        packageUnit: '',
        skuQty: '',
        mfgName: '',
        sn: '',
        udi: '',
        rfid: ''
      },
      txtScan: '',
      // btnUnbindDisabled: true,
      btnPrintDisabled: true,
      propInitData: [],
      udi: ''
    }
  },
  name: 'udibind',
  mounted() {
    this.$refs.txtScan.focus()
  },
  methods: {

    //扫码SN或RFID
    async barCodeScan() {
      await this.utilVue.loadShow(true)
      //校验条码
      if (!this.txtScan) {
        this.utilVue.loadHide()
        this.$refs.txtScan.focus()
        this.utilMessage.warning(' 请扫描条码进行查询')
        return
      }
      //校验条码类型
      let codeType = barcodeParse.barCodeType(this.txtScan)
      if (!codeType || (codeType != 'SN' && codeType != 'GTIN' && codeType != 'RFID')) {
        await this.utilVue.loadHide()
        this.$refs.txtScan.focus()
        this.utilMessage.error(' 条码【' + this.txtScan + '】类型非法')
        return
      }
      //数据加载过并且扫描的是UDI
      if (codeType == 'GTIN') {
        if (this.txtScan.length > 16 && this.txtScan.substring(0, 2) == '01') {
          this.udi = this.txtScan
          if (this.form.id) {
            if (this.form.udi) {
              this.getStockListByUdi(this.udi)
            } else {
              this.txtScan = ''
              this.form.udi = this.udi
            }
          } else {
            this.getStockListByUdi(this.udi)
          }
        } else {
          this.udi = this.udi + this.txtScan
          this.txtScan = ''
          this.form.udi = this.udi
        }
        setTimeout(() => {
          this.utilVue.loadHide()
        }, 100)
        return false
      }
      if (codeType == 'SN') {
        this.$ajax.get(`wm/stock/getStockByUCOnly?uc=${this.txtScan}`).then((response) => {
          //获取耗材成功
          if (response.code == 0) {
            //校验仓库
            if (response.data.warehouseId != this.utils.getCurrentWarehouse().id) {
              this.utilMessage.error('该耗材不属于该仓库不允许绑定')
              this.utilVue.loadHide()
              return false
            }
            if (this.propInitData.length != 0 && this.form.id) {
              this.checkStock(response.data)
            } else {
              this.addStock(response.data)
            }
            this.utilVue.loadHide()
          }
        }).catch(() => {
          this.utilVue.loadHide()
        })
      }
      if (codeType == 'RFID') {
        this.$ajax.get(`wm/stock/getStockListByUniqueCode?uniqueCode=${this.txtScan}`).then((response) => {
          if (response.code == 0) {
            if (response.data.length != 0) {
              if (this.form.id) {
                this.utilMessage.success(response.msg)
                this.txtScan = ''
                let stocks = response.data
                stocks.forEach((stock) => {
                  this.checkStock(stock)
                  this.refreshData()
                })
              } else {
                let stocks = response.data
                stocks.forEach((stock) => {
                  this.form = stock
                  this.addStock(stock)
                })
                this.refreshData()
              }
            } else {
              this.utilVue.loadHide()
              this.utilMessage.error('该RFID未绑定任何SN,请先扫描SN')
              this.$refs.txtScan.focus()
            }
            this.utilVue.loadHide()
          }
          // this.showButton()
          this.utilVue.loadHide()
        })
        this.utilVue.loadHide()
      }
    },
    checkStock(stock) {
      if (stock.matrId != this.form.matrId) {
        this.utilMessage.error('该耗材与之前扫描的耗材不为同一耗材，不能绑定')
        this.utilVue.loadHide()
        return false
      } else if (stock.lot != this.form.lot) {
        this.utilMessage.error('该耗材与之前扫描的耗材批次不同，不能绑定')
        this.utilVue.loadHide()
        return false
      } else if (stock.expDate != this.form.expDate) {
        this.utilMessage.error('该耗材与之前扫描的耗材效期不同，不能绑定')
        this.utilVue.loadHide()
        return false
      } else {
        this.addStock(stock)
      }
    },
    extraButtonClick(para) {
      let buttonKey = para.button.key
      if (buttonKey === 'delete') {
        this.propInitData.splice(this.propInitData.indexOf(para.data.sn), 1)
        this.refreshData()
        this.utilVue.loadHide()
      } else if (buttonKey === 'unbind') {
        this.$ajax.get(`wm/stock/udiBindOrUnbind?opType=unbind&snstr=${para.data.sn}&udi=null`).then((response) => {
          if (response.code == 0) {
            this.utilMessage.success(response.msg)
            this.form.udi = ''
            this.txtScan = ''
            this.$refs.txtScan.focus()
            // this.btnUnbindDisabled = true
            this.propInitData.indexOf(para.data.sn)
            this.propInitData.splice(this.propInitData.indexOf(para.data.sn), 1)
            this.refreshData()
          } else {
            this.utilMessage.error(response.msg)
          }
          this.utilVue.loadHide()
        })
      }
    },
    //查询明细数据
    refreshData() {
      let queryWrapper = this.$newWrapper()
      if (this.propInitData.length != 0) {
        queryWrapper.in('sn', this.propInitData)
        this.$refs.dataViewSN.setQueryWrapper(queryWrapper)
      } else {
        Object.keys(this.form).forEach(key => (this.form[key] = ''))
        this.txtScan = ''
        this.$refs.txtScan.focus()
        this.$refs.dataViewSN.$refs.tbMain.loadData([])
        this.$refs.dataViewSN.tablePage.totalResult = 0
      }
    },
    //绑定udi
    bind() {
      this.$ajax.get(`wm/stock/udiBindOrUnbind?opType=bind&snstr=${this.propInitData}&udi=${this.udi}`).then((response) => {
        if (response.code == 0) {
          Object.keys(this.form).forEach(key => (this.form[key] = ''))
          this.txtScan = ''
          this.udi = ''
          this.$refs.txtScan.focus()
          this.utilMessage.success('绑定成功')
        }
        this.utilVue.loadHide()
        this.refreshData()
      }).catch(() => {
        this.utilVue.loadHide()
      })
    },
    reset() {
      // this.btnUnbindDisabled = true
      Object.keys(this.form).forEach(key => (this.form[key] = ''))
      this.txtScan = ''
      this.udi = ''
      this.$refs.txtScan.focus()
      this.$refs.dataViewSN.$refs.tbMain.loadData([])
      this.$refs.dataViewSN.tablePage.totalResult = 0
      this.propInitData = []
    },
    getStockListByUdi(udi) {
      this.propInitData = []
      this.$ajax.get(`wm/stock/getStockListByUdi?udi=${udi}`).then((response) => {
        if (response.code == 0) {
          if (this.form.udi) {
            Object.keys(this.form).forEach(key => (this.form[key] = ''))
          }
          if (response.data.length != 0) {
            this.utilMessage.success(response.msg)
            this.txtScan = ''
            this.udi = ''
            let stock = response.data
            stock.forEach((stock) => {
              this.form = stock
              this.propInitData.push(this.form.sn)
              this.refreshData()
            })
            this.propInitData = []
          } else {
            this.utilMessage.error('该UDI未绑定任何SN,请先扫描SN')
            this.$refs.txtScan.focus()
          }
        }
        Object.keys(this.form).forEach(key => (this.form[key] = ''))
        this.utilVue.loadHide()
      }).catch(() => {
        this.utilVue.loadHide()
      })
    },
    addStock(stock) {
      //已经有明细且通过唯一码已查询到库存且库存已有udi
      if (!this.strings.isBlank(stock.udi) && this.form.id && this.propInitData.length != 0) {
        this.utilMessage.error('该库存已经绑定UDI,请解绑再绑定')
        this.utilVue.loadHide()
        return false
      } else {
        if (this.form.udi || !this.form.id) {
          this.propInitData = []
        }
        this.txtScan = ''
        if (stock) {
          this.form = stock
          this.propInitData.push(this.form.sn)
          this.refreshData()
          if (stock.udi) {
            Object.keys(this.form).forEach(key => (this.form[key] = ''))
          }
          this.btnPrintDisabled = false
        } else {
          // this.btnUnbindDisabled = true

          this.$refs.txtScan.focus()
        }
      }
    },
    resetUdi() {
      this.form.udi = ''
    }
  }
}
</script>
<style lang="scss" scoped>
  .udibind{
    min-width: 1200px;
    .el-form{
      width: 100%;

      .el-form-item{
      }
    }
  }
</style>
